import { authHandler } from './handlers/auth'
import { passwordHandler } from './handlers/password'
import { noteHandler } from './handlers/note'
import { corsHeaders } from './utils/cors'
import { verify } from '@tsndr/cloudflare-worker-jwt'
import { Logger } from './utils/logger'

// 不需要验证token的路由
const publicPaths = [
  '/api/auth/challenge',
  '/api/auth/login',
  '/api/auth/forgot-password',
  '/api/auth/check-user'
];

// 验证token的中间件
async function authenticateToken(request, env) {
  const authHeader = request.headers.get('Authorization');
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return new Response(JSON.stringify({ error: '未授权访问' }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }

  const token = authHeader.split(' ')[1];
  try {
    const isValid = await verify(token, env.JWT_SECRET);
    if (!isValid) {
      return new Response(JSON.stringify({ error: 'token无效' }), {
        status: 401,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }

    // 解析token获取用户信息
    const payload = JSON.parse(atob(token.split('.')[1]));
    request.user = { 
      email: payload.email,
      userId: payload.userId
    };
    return null;
  } catch (error) {
    return new Response(JSON.stringify({ error: 'token验证失败' }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }
}

async function handleRequest(request, env, ctx) {
  const logger = new Logger(env).setModule('handleRequest');
  const url = new URL(request.url)
  const path = url.pathname
  logger.info('请求路径和方法', { path, method: request.method });
  // 处理OPTIONS请求
  if (request.method === 'OPTIONS') {
    return new Response(null, {
      status: 204,
      headers: corsHeaders
    })
  }

  // 对非公开路由进行token验证
  if (!publicPaths.includes(path)) {
    const authError = await authenticateToken(request, env);
    if (authError) return authError;
  }

  // 认证相关路由
  if (path.startsWith('/api/auth/')) {
    switch(path) {
      case '/api/auth/challenge':
        return request.method === 'POST' ? authHandler.getChallenge(request, env) : null;
      case '/api/auth/login':
        return request.method === 'POST' ? authHandler.login(request, env) : null;
      case '/api/auth/forgot-password':
        return request.method === 'POST' ? authHandler.forgotPassword(request, env) : null;
      case '/api/auth/encrypt-salt':
        return request.method === 'GET' ? authHandler.getEncryptSalt(request, env) : null;
      case '/api/auth/check-user':
        return request.method === 'POST' ? authHandler.checkUser(request, env) : null;
      default:
        break;
    }
  }

  // 密码相关路由
  if (path.startsWith('/api/passwords')) {
    if (request.method === 'GET' && path === '/api/passwords/count') {
      return passwordHandler.handleGetPasswordCount(request, env);
    }
    if (path.match(/^\/api\/passwords\/\d+\/detail$/)) {
      // 获取密码详情
      const id = path.split('/')[3];
      request.params = { id };
      return request.method === 'GET' ? passwordHandler.getDetail(request, env) : null;
    } else if (path.match(/^\/api\/passwords\/\d+$/)) {
      // 更新或删除密码
      const id = path.split('/')[3];
      request.params = { id };
      if (request.method === 'PUT') {
        return passwordHandler.update(request, env);
      } else if (request.method === 'DELETE') {
        return passwordHandler.delete(request, env);
      }
    } else if (request.method === 'GET') {
      return passwordHandler.list(request, env)
    } else if (request.method === 'POST') {
      return passwordHandler.create(request, env)
    }
  }

  // 笔记相关路由
  if (path.startsWith('/api/notes')) {
    if (request.method === 'GET') {
      return noteHandler.list(request, env)
    } else if (request.method === 'POST') {
      return noteHandler.create(request, env)
    } else if (request.method === 'PUT') {
      return noteHandler.update(request, env)
    } else if (request.method === 'DELETE') {
      return noteHandler.delete(request, env)
    }
  }

  return new Response('Not Found', { 
    status: 404, 
    headers: corsHeaders 
  })
}

export default {
  async fetch(request, env, ctx) {
    console.log('fetch');
    try {
      return await handleRequest(request, env, ctx)
    } catch (error) {
      console.error('Error handling request:', error)
      return new Response('Internal Server Error', { 
        status: 500, 
        headers: corsHeaders 
      })
    }
  }
}